package logic

import (
	"context"
	"errors"
	"video-hub/models/mysql"

	"video-hub/videorpc/internal/svc"
	"video-hub/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectDelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectDelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectDelLogic {
	return &CollectDelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 取消收藏与数据同步
func (l *CollectDelLogic) CollectDel(in *videorpc.CollectDelRequest) (*videorpc.CollectDelResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	err := findUser.FirstUserById(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("请先登录")
	}
	var video mysql.Video
	err = video.FirstVideoById(mysql.DB, in.VideoId)
	if err != nil {
		return nil, errors.New("该视频不存在")
	}
	var findCollect mysql.Collect
	err = findCollect.FindUserIdAndVideoId(mysql.DB, in.VideoId, in.UserId)
	if err != nil {
		return nil, err
	}
	if findCollect.ID == 0 {
		return nil, errors.New("未收藏该视频")
	}
	err = findCollect.DelCollect(mysql.DB, in.UserId, in.VideoId)
	if err != nil {
		return nil, errors.New("取消收藏失败")
	}
	err = mysql.UpdateCollectNumDel(mysql.DB, in.VideoId)
	if err != nil {
		return nil, errors.New("收藏-1失败")
	}
	return &videorpc.CollectDelResponse{}, nil
}
